//
//  InformationInputViewController.m
//  Doctors
//
//  Created by 王森 on 16/4/19.
//  Copyright © 2016年 王森. All rights reserved.
//

#import "InformationInputViewController.h"
#import "InformationInputTableViewCell.h"
#import "PlaceAndTimeTableViewCell.h"
#import "uploadOrderTableViewCell.h"
#import "SubmitTableViewCell.h"
#import "UIView+BlockGesture.h"
#import "UIImage+FX.h"
#import "KTSelectDatePicker.h"
#import "HospitalViewController.h"

@interface InformationInputViewController ()<UIPickerViewDelegate,UIActionSheetDelegate>

{
    NSArray *titleArray;
    NSMutableArray *placeHolderArray;
    UIImage *tempImg;
    BOOL isHiddenTItle;
    
}
@property (strong, nonatomic) KTSelectDatePicker *selectPicker;

@end

@implementation InformationInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBackBtn:nil];
    self.title=@"信息录入";
    isHiddenTItle=NO;
    
    tempImg=[UIImage imageNamed:@"shangchuanzhaopian"];
    
    titleArray=@[@"姓  名:",@"医保号:",@"手机号 :",@"录入点:",@"时  间:",@"医疗费(元):",@"草药费(元):",@"其他费:",@"医  师:",@"病情描述:",@"订单上传",@"提交"];
    
    NSArray *tempArray=@[@"请输入姓名",@"请输入医保号",@"请输入手机号",@"请设置录入点",@"请设置时间",@"请输入医疗费",@"请输入草药费",@"请输入其他费用",[self getArtisanName],@"可选写",@"订单上传",@"提交"];
    placeHolderArray = [NSMutableArray arrayWithArray:tempArray];
    
    __weak typeof(self) weakSelf = self;
    
    [self initWithTableViewNib:@"InformationInputTableViewCell" didSelectCellBlock:^(NSIndexPath *indexPath) {
        [weakSelf didselectRow:indexPath];
        
        
    }];
    [self registerNib:@"PlaceAndTimeTableViewCell"];
    [self registerNib:@"uploadOrderTableViewCell"];
    [self registerNib:@"SubmitTableViewCell"];
    
    
    
    
    // Do any additional setup after loading the view.
}

-(void)viewWillDis8appear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
    
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    [self.view endEditing:YES];
//
//}
/**
 *  提交按钮
 */
-(void)submitBtnPress{
    
    
    
    UITextField *text0=[self.view viewWithTag:200];
    UITextField *text1=[self.view viewWithTag:201];
    UITextField *text2=[self.view viewWithTag:202];
    UITextField *text5=[self.view viewWithTag:205];
    UITextField *text6=[self.view viewWithTag:206];
    UITextField *text7=[self.view viewWithTag:207];
    UITextField *text8=[self.view viewWithTag:208];
    UITextField *text9=[self.view viewWithTag:209];
    
    if ([self validText:text0.text]&&[self validText:text1.text]&&[self validText:text2.text]&&[self validText:text5.text]&&[self validText:text6.text]&&[self validText:text7.text]&&[self validText:text8.text]&&[self validText:_time]&&[self validText:_imgUrlstring]&&[self validText:_hospitalID]) {
        NSLog(@"图片路径：%@",_imgUrlstring);
        
        NSMutableDictionary *dictionary=[NSMutableDictionary dictionary];
        [dictionary setObject:[self getArtisanId] forKey:@"artisanId"];
        
        [dictionary setObject:text0.text forKey:@"username"];
        [dictionary setObject:text2.text forKey:@"mobile"];
        [dictionary setObject:text1.text forKey:@"medicareCard"];
        [dictionary setObject:_hospitalID forKey:@"hospital"];
        
        [dictionary setObject:_time forKey:@"createTime"];
        
        [dictionary setObject:[NSString stringWithFormat:@"%.2f",[text5.text  floatValue]*100] forKey:@"amount"]
        ;
        [dictionary setObject:[NSString stringWithFormat:@"%.2f",[text6.text  floatValue]*100] forKey:@"herbalAmt"];
        
        
        
        [dictionary setObject:[NSString stringWithFormat:@"%.2f",[text7.text  floatValue]*100] forKey:@"otherAmt"];
        [dictionary setObject:text8.text forKey:@"openOrder"];
        
        [dictionary setObject:text9.text forKey:@"describe"];
        [dictionary setObject:@"6" forKey:@"channel"];
        [dictionary setObject:_imgUrlstring forKey:@"fileUrl"];
        
        [self showWithStatus:@"正在提交请求"];
        
        [self requestApiWithUrl:@"/user/inputInfo" dictionary:dictionary isCache:NO success:^(id responseObject) {
            [self removeStatuslable];
            
            [self showSuccess:@"录入成功"];
            if (_reloadData) {
                
                _reloadData();
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            
            NSLog(@"===%@",responseObject);
            
            
        } faild:^(NSError *error) {
            [self removeStatuslable];

        }];
        
        
    }
    else
    {
        [self.view makeToast:@"请检查信息是否完整"];
    }
    
    
    NSLog(@"%@--%@--%@--%@--%@--%@--%@--%@--%@",_time,text0.text,text1.text,text2.text,text5.text,text6.text,text7.text,text8.text,text9.text);
    
    
}


-(BOOL )validText:(NSString *)string
{
    
    return ![string isEqualToString:@""]&&![string isEqual: @"(null)"]&&string !=NULL &&string!=nil?YES:NO;
    
    
}

-(void)didselectRow:(NSIndexPath *)index
{        __weak typeof(self) weakSelf = self;
    
    
    if (index.row==3) {
        ALLOC(HospitalViewController, view);
        [view setSelectIndexName:^(NSArray *arrayString) {
            
            _hospitalString=arrayString[0];
            
            _hospitalID=[NSString stringWithFormat:@"%@",arrayString[1]];
            
            
            
            [placeHolderArray replaceObjectAtIndex:3 withObject:_hospitalString];
            NSIndexPath *index=[NSIndexPath indexPathForRow:3 inSection:0];
            NSArray *array=@[index];
            [weakSelf.tableview reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
            
            
        }];
        
        [self pushNextViewController:view];
    }
    
    if (index.row==4) {
        [self.view endEditing:YES];

        _selectPicker = [[KTSelectDatePicker alloc] init];
        [_selectPicker didFinishSelectedDate:^(NSDate *selectedDate) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSString *currentOlderOneDateStr = [dateFormatter stringFromDate:selectedDate];
            [placeHolderArray replaceObjectAtIndex:4 withObject:currentOlderOneDateStr];
            _time=currentOlderOneDateStr;
            
            NSIndexPath *index=[NSIndexPath indexPathForRow:4 inSection:0];
            NSArray *array=@[index];
            [weakSelf.tableview reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
            
            
        }];
        
        
        
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.row<3||(indexPath.row>4&&indexPath.row<10)) {
        InformationInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InformationInputTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.title.text=titleArray[indexPath.row];
        
        cell.textInput.placeholder=placeHolderArray[indexPath.row];
        if (indexPath.row>0&&indexPath.row<3) {
            cell.textInput.keyboardType=UIKeyboardTypeNumberPad;
            
        }
        if (indexPath.row>4&&indexPath.row<8) {
            cell.textInput.keyboardType=UIKeyboardTypeNumberPad;
            
        }
        cell.textInput.tag=indexPath.row+200;
          if (indexPath.row==8) {
                    cell.textInput.text=placeHolderArray[indexPath.row];
 
                }

        
        return cell;
        
    }
    if (indexPath.row>2&&indexPath.row<5) {
        PlaceAndTimeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PlaceAndTimeTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.title.text=titleArray[indexPath.row];
        cell.content.text=placeHolderArray[indexPath.row];
        cell.content.tag=indexPath.row+300;
        
        return cell;
        
        
    }
    
    if (indexPath.row==10) {
        uploadOrderTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"uploadOrderTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        //        cell.uploadImg.userInteractionEnabled=YES;
        
        cell.uploadImg.image=tempImg;
        
        [cell.delegateImg addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            isHiddenTItle=NO;
            
            tempImg=[UIImage imageNamed:@"shangchuanzhaopian"];
            cell.tmpTItle.hidden=NO;
            //    [self.tableview reloadData];
            NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:10 inSection:0];
            //    NSIndexPath *index=[NSIndexPath indexPathWithIndex:10];
            NSArray *arr=@[indexPath_1];
            [self.tableview reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
            
        }];
        
        
        cell.tmpTItle.hidden=isHiddenTItle;
        
        cell.delegateImg.hidden=!isHiddenTItle;
        
        [cell.uploadImg addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            cell.tmpTItle.hidden=YES;
            
            isHiddenTItle=YES;
            UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                          initWithTitle:@"请选择一种方式"
                                          delegate:self
                                          cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                          otherButtonTitles:@"相机",@"本地相册",nil];
            [actionSheet showInView:self.view];
            
            
            
        }];
        
        return cell;
        
    }
    //    else (indexPath.row==11) {
    //        SubmitTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"SubmitTableViewCell" forIndexPath:indexPath];
    //        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    //
    //        return cell;
    //
    //    }
    //
    else{
        SubmitTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SubmitTableViewCell" forIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        [cell.submitBtn addTarget:self action:@selector(submitBtnPress) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 12;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==10) {
        //        return 167;
        
        return isHiddenTItle?143:167;
        
    }
    
    if (indexPath.row==11) {
        
        
        return 70;
    }
    else
        return 49;
    
}




#pragma mark - 判断设备是否有摄像头 设置用户头像

- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

#pragma mark -
#pragma UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    
    
    if (buttonIndex == 0)//照相机
    {
        if ([self isCameraAvailable]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            NSLog(@"没有摄像头");
            
            [self showFailed:@"没有摄像头"];
            //           [PublicMethod showMBProgressHUD:@"该设备没有摄像头" andWhereView:self.view hiddenTime:kHiddenTime];
        }
    }
    if (buttonIndex == 1)
    {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //scale这个参数从0.1开始逐渐等比放大图片
    NSLog(@"%2f---%2f",image.size.height,image.size.width);

    UIImage *newimage = [image makeThumbnailFromImage:image scale:0.3];
    
    NSLog(@"%f---%f",newimage.size.height,newimage.size.width);
    
    
    [NSThread detachNewThreadSelector:@selector(saveImage:) toTarget:self withObject:newimage];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveImage:(UIImage *)image
{
    //    UIImageView *images=(UIImageView *)[self.view viewWithTag:88];
    //    images.image=image;
    tempImg=image;
    
    
    //    [self.tableview reloadData];
    NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:10 inSection:0];
    //    NSIndexPath *index=[NSIndexPath indexPathWithIndex:10];
    NSArray *arr=@[indexPath_1];
    [self.tableview reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [self uploadImg:image];
    
    
    
    
}

-(void)uploadImg:(UIImage *)image
{
    
    
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        

        [self showWithStatus:@"正在上传图片"];

        NSString *string=[self image2DataURL:image];
        
        
        [self requestApiWithUrl:@"/user/uplodaFile" dictionary:@{@"imgData":string} isCache:NO success:^(id responseObject) {
            
            NSLog(@"请求回调结果：%@",responseObject);
            [self removeStatuslable];
            
            [self showSuccess:@"图片上传成功"];
            _imgUrlstring=responseObject[@"fileUrl"];
            
        } faild:^(NSError *error) {
            NSLog(@"====请求失败：%@",error);
            
        }];
        
//    });
    
}

- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image,0.3f);
        mimeType = @"image/jpeg";
    }
    
    return [NSString stringWithFormat:@"%@",
            [imageData base64EncodedStringWithOptions: 0]];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
